package com.fs.service.Impl;

import com.fs.constant.MessageConstant;
import com.fs.constant.StatusConstant;
import com.fs.dto.EmployeeDTO;
import com.fs.dto.EmployeeLoginDTO;
import com.fs.dto.EmployeePageQueryDTO;
import com.fs.dto.EmployeeRegisterDTO;
import com.fs.entity.Employee;
import com.fs.exception.PasswordErrorException;
import com.fs.mapper.EmployeeMapper;
import com.fs.result.PageResult;
import com.fs.service.EmployeeService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.util.DigestUtils;

import javax.security.auth.login.AccountLockedException;
import javax.security.auth.login.AccountNotFoundException;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {


    @Autowired
    private EmployeeMapper employeeMapper;

    /*注册新员工*/
    public String save(EmployeeRegisterDTO employeeRegisterDTO) {
        String md5DigestAsHex = DigestUtils.md5DigestAsHex(employeeRegisterDTO.getPassword().getBytes());
        Employee employee = new Employee();
        //对象属性拷贝
        BeanUtils.copyProperties(employeeRegisterDTO, employee);
        //设置用户状态
        employee.setStatus(1);
        //设置密码
        employee.setPassword(md5DigestAsHex);
        //创建时间、更新时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        log.info("注册员工：{}",employee);
        Integer flag =employeeMapper.register(employee);

        if (flag == 1){
            return MessageConstant.REGISTER_SUCCESS;
        }else {
            return MessageConstant.REGISTER_ERROR;
        }
    }

    /*员工登录*/
    @SneakyThrows
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /*根据id显示员工信息*/
    public Employee getById(Long id) {
        Employee employee = employeeMapper.getById(id);
        employee.setPassword("****");
        return employee;
    }

    /*更新员工资料*/
    public String update(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        //拷贝对象信息
        BeanUtils.copyProperties(employeeDTO,employee);

        employee.setUpdateTime(LocalDateTime.now());

        Integer flag = employeeMapper.update(employee);
        if (flag == 1){
            return MessageConstant.UPDATE_SUCCESSFUL;
        }else {
            return MessageConstant.UPDATE_FAILED;
        }
    }

    /*删除员工*/
    public String deleteByIds(List<Long> ids) {
        //1.判断ids是否为空  不为空：执行删除操作
        if (ids == null || ids.size() == 0) {
            return MessageConstant.UNKNOWN_ERROR;
        }else {
            Integer flag = employeeMapper.deleteByIds(ids);
            if (flag != 0){
                return MessageConstant.DELETE_SUCCESSFUL;
            }else {
                return MessageConstant.UNKNOWN_ERROR;
            }
        }
    }


    /*分页查询员工*/
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //开始分页查询
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);
        long total = page.getTotal();
        List<Employee> records = page.getResult();
        PageResult pageResult = new PageResult(total,records);
        return pageResult;
    }

    /*启用禁用员工证号*/
    public void startOrStop(Integer status, Long id) {
        Employee employee =  Employee.builder()
                .status(status).id(id).build();
        employeeMapper.update(employee);
    }

}
